/* utils */
import * as TaskApi from '@src/api/TaskApi.ts';
import { getRootWindow } from '@src/util/dom'
import i18n from '@src/locales'
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()
export default {
  inject: ['initData'],
  data() {
    return {
      finalTotalAmount: 0,
      settlementRulesList: {}, // 工单结算规则
      settlementRulesLen: 0,
      internationalGray
    };
  },
  computed: {
    // 工单规则费用合计 - 获取后端的数据
    taskRuleSettlement() {
      const arr = this.initData?.receiptTaskForUpdate?.taskSettlement || [];

      // 后端数据进行处理
      let apiMap = {}
      if (Array.isArray(arr) && arr.length) {
        arr.forEach(item => {
          const ruleFlag = this.getRuleFlagByRuleSettlement(item)
          apiMap[ruleFlag] = item
        })
      }

      return apiMap;
    },

    // 工单规则费用合计 - 获取后端的数据 用于详情表格的展示
    taskRuleSettlementDetail() {
      const arr = this.initData?.receiptTaskForUpdate?.taskSettlement || [];
      return arr
    },
    // 服务项目折扣灰度
    isServiceItemDiscountSettings() {
      const RootWindow = getRootWindow(window)
      return Boolean(RootWindow.grayAuth?.serviceItemDiscountSettings)
    },

    // 费用总计计算
    receiptRulesList() {
      let { materialVerifyEliminate, serviceIterm, sparepart } = this.form || {};

      let saveObj = {}

      // 备件
      if (Array.isArray(sparepart) && sparepart.length > 0) {
        sparepart.forEach(item => {
          saveObj = this.handleData(item, saveObj, 'sparepart');
        })
      }

      // 物料核销
      if (Array.isArray(materialVerifyEliminate) && materialVerifyEliminate.length > 0) {
        materialVerifyEliminate.forEach(item => {
          saveObj = this.handleData(item, saveObj, 'material');
        })
      }

      // 服务费用
      if (Array.isArray(serviceIterm) && serviceIterm.length > 0) {
        serviceIterm.forEach(item => {
          saveObj = this.handleData(item, saveObj, 'service');
        })
      }
  

      let result = []
      //生成结果，并保留两位小数
      for (let mapKey in saveObj) {
        //后端返回了对应规则，需要将其折扣金额覆盖掉 - 保内收费/保外收费折扣费用支持手动输入所以需要特殊处理
        if (Object.hasOwnProperty.call(this.taskRuleSettlement, mapKey) && (mapKey === 'rule1' || mapKey === 'rule3')) {
          saveObj[mapKey].disExpense = Number(this.taskRuleSettlement[mapKey]?.disExpense);
          //重新计算总价
          saveObj[mapKey].totalExpense = Number(saveObj[mapKey]?.materialTotal) + Number(saveObj[mapKey]?.serviceTotal) - Number(saveObj[mapKey]?.disExpense);
        }
        
        //处理小数位数
        saveObj[mapKey].materialTotal = Number(saveObj[mapKey]?.materialTotal)?.toFixed(2);
        saveObj[mapKey].serviceTotal = this.isServiceItemDiscountSettings ? Number(this.serviceTotal)?.toFixed(2) : Number(saveObj[mapKey]?.serviceTotal)?.toFixed(2);
        saveObj[mapKey].disExpense = Number(saveObj[mapKey]?.disExpense)?.toFixed(2);
        saveObj[mapKey].totalExpense = Number(saveObj[mapKey]?.totalExpense)?.toFixed(2);
        result.push(saveObj[mapKey]);
      }
      
      return result;
    },
    // 结算规则灰度
    isSettlementRule() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.settlementRule || false
    }, 
    isShowSettlementRules() {
      return this.isSettlementRule && this.settlementRulesLen && !this.isBgiPrivate // 华大基因默认走老的费用合计
    }
  },
  provide() {
    return {
      fetchRuleList: this.fetchRuleList
    }
  },
  methods: {
    // charge 收费 free 免费
    // IN 保内 OUT 保外
    // 规则1: 保内收费
    // 规则2: 保内免费
    // 规则3: 保外收费
    // 规则4: 保外免费
    getRuleFlagByRuleSettlement(item) {
      const ruleFlagMap = {
        'IN_charge': 'rule1',
        'IN_free': 'rule2',
        'OUT_charge': 'rule3',
        'OUT_free': 'rule4'
      }

      return ruleFlagMap[`${item.qualityStatus}_${item.isFree}`]
    },
    // 数据处理
    handleData(item, map, type) {
      var ruleFlag = '';

      ruleFlag = this.getRuleFlagByRuleSettlement(item)

      //没有合适的规则直接返回
      if (ruleFlag === '') {
        return map;
      }

      var tmpOne = {
        settlementRules: item.settlementRules, // 结算规则
        isFree: item.isFree, // 收费/免费
        isFreeName: item.isFree === 'free' ? i18n.t('zhongqi.setting.free')  : i18n.t('zhongqi.setting.charge'),
        qualityStatus: item.qualityStatus,
        //这四个元素，相同的规则需要累计处理
        ruleId: [item.settlementRulesId],
        materialTotal: 0, // 物料费用
        serviceTotal: 0, // 服务费用
        disExpense: 0, //折扣费用
        totalExpense: 0, //总计费用
      };
      
      if (type === 'material' && this.isMaterialFee) {
        //物料中服务费用为0
        tmpOne.materialTotal = item.number * item.salePrice;
        if(internationalGray) tmpOne.materialTotal = item.number * item.salePrice * item.exchangeRate
      } else if (type === 'service' && !this.isFreeServiceFee) {
        //服务中物料费用为0
        tmpOne.serviceTotal = item.number * item.salePrice;
        if(internationalGray) tmpOne.serviceTotal = item.number * item.salePrice * item.exchangeRate
      }

      if (item.isFree === 'free') {
        tmpOne.disExpense = tmpOne.materialTotal + tmpOne.serviceTotal;
      }

      tmpOne.totalExpense = tmpOne.materialTotal + tmpOne.serviceTotal - tmpOne.disExpense;

      if (!map.hasOwnProperty(ruleFlag)) {
        map[ruleFlag] = tmpOne;
      } else {
        //防止重复
        if (!map[ruleFlag].ruleId.includes(item.settlementRulesId)) {
          map[ruleFlag].ruleId.push(item.settlementRulesId);
        }
        map[ruleFlag].materialTotal += tmpOne.materialTotal;
        map[ruleFlag].serviceTotal += tmpOne.serviceTotal;
        map[ruleFlag].disExpense += tmpOne.disExpense;
        map[ruleFlag].totalExpense += tmpOne.totalExpense;
      }
      return map;
    },
    // 是否计算物料费用
    isMaterialFee() {
      // 按照产品需求：物料先用质保的配置 后续是否需要添加物料的配置待定
      let calculateCost = this.hasQuality && this.isFreeMaterialFee && item.warrantyStatus === '保内';
      return !calculateCost;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const len = columns.length;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = i18n.t('task.detail.components.totalReceivables');
          return;
        } else if (index === len - 1) {
          const values = data.map(item => Number(item[column.property]));
          let ret = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          let count = ret.toFixed(2);
          if (column.property == 'totalExpense' && this.taskRuleSettlementDetail.length > 1) {
            count = count * 1 + this.sparepartTotal * 1
          }
          if(internationalGray) {
            let currency = this.currencyType || this.settlementCurrency || 'CNY'
            sums[index] = `${count} ${currency}`;
          }else {
            sums[index] = count;
          }
          this.finalTotalAmount = Number(count).toFixed(2);
        }
      });

      return sums;
    },
    // 获取规则
    async fetchRuleList() {
      let params = {
        moduleId: this.task?.templateId
      }
      let res = await TaskApi.getSettlementRuleModule(params)

      if (!res.success) return;

      this.settlementRulesList = res.result;

      let { materialVerifyEliminate, serviceIterm } = res?.result || {};
      
      let arr = [...(materialVerifyEliminate || []), ...(serviceIterm || [])]

      this.settlementRulesLen = !!arr?.length;
    },
    // 合并最后一行单元格 表尾合计行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // console.log('rowIndex', rowIndex) // 表尾合计行的 rowIndex 获取不到
      // 目前用这种方式处理
      this.$nextTick(() => {
        if (this.$refs.tableRef.$el) {
          let current = this.$refs.tableRef.$el
              .querySelector(".el-table__footer-wrapper")
              .querySelector(".el-table__footer");
          
          let cell = current.rows[0].cells;
          cell[0].className = 'total-row-table-last-line';
          cell[1].style.display = "none";
          cell[2].style.display = "none";
          if (this.showMaterialVerifyEliminate && this.showService) {
            cell[0].colSpan = "5";
            cell[3].style.display = "none";
            cell[4].style.display = "none";
          } else if ((this.showMaterialVerifyEliminate && !this.showService) || (!this.showMaterialVerifyEliminate && this.showService)) {
            cell[0].colSpan = "4";
            cell[3].style.display = "none";
          } else if (!this.showMaterialVerifyEliminate && !this.showService) {
            cell[0].colSpan = "3";
          }
        }
      })
    }
  },
};
